package com.etone.smartAudit.annotation.support;

import com.etone.smartAudit.annotation.LoginAdmin;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.AdminMapper;
import com.etone.smartAudit.security.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import static org.zalando.problem.Status.FORBIDDEN;

/**
 * @author: 蒋学伟
 * @date: 2018/10/15
 * @description:
 */
@Component
public class LoginAdminHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(Admin.class) && methodParameter.hasParameterAnnotation(LoginAdmin.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String loginAdminName = SecurityUtils.getCurrentUserLogin();
        Admin admin = adminMapper.findByAccount(loginAdminName);
        if (admin == null) {
            throw new CustomParameterizedException("用户不存在，非法操作", FORBIDDEN);
        }
        return admin;
    }
}
